var auth = require('../../helpers/auth.js');
var db = require('../../models/index.js');
var render = require('../../instances/render.js');
var debug = require('../../instances/debug.js');
var util = require('util');
var co = require('co');

var sequelizex = require('../../lib/sequelizex.js');

var ShoppingCart = db.models.ShoppingCart;

//全部都要加上shopID

module.exports = (router) => {

    router.get('/user/shoppingcart/:id/:num/:shopId', function *() {
        this.checkParams('id').notEmpty().isInt().toInt();
        this.checkParams('num').notEmpty().isInt().toInt();
        this.checkParams('shopId').notEmpty().isInt().toInt();
        if (this.errors) {
            this.body = this.errors;
            return;
        }
        var shoppingCart = yield ShoppingCart.findOne({
            where:{
                UserId: (yield auth.user(this)).id,
                GoodId: this.params.id,
                shopId: this.params.shopId
            }
        });
        debug('shoppingCart:' + shoppingCart);
        debug('params:' + this.params.id + "/" + this.params.num + "/" + this.params.shopId);
        if (shoppingCart) {
            if (this.params.num >= 0 ) {
                shoppingCart.num = this.params.num;
                yield shoppingCart.save();
            } else {
                yield shoppingCart.destroy();
            }
        } else if (this.params.num >= 0){
            yield ShoppingCart.create({
                UserId: (yield auth.user(this)).id,
                GoodId: this.params.id,
                num: this.params.num,
                shopId: this.params.shopId
            });
        }
        this.body = 'ok';
    });

    router.get('/user/shoppingcart/all/:shopId', function *() {
        this.checkParams('shopId').notEmpty().isInt().toInt();
        if(this.errors){
            this.body = this.errors;
            return;
        }
        this.body = sequelizex.Func.val(yield ShoppingCart.findAll({
            where: {
                UserId: (yield auth.user(this)).id,
                shopId: this.params.shopId
            },
            attributes: ['id', 'num', 'GoodId']
        }));
    });

    router.get('/user/shoppingcart/:shopId',function *(){
        this.checkParams('shopId').notEmpty().isInt().toInt();
        if (this.errors) {
            this.body = this.errors;
            return;
        }
        var totalprice = 0;
        var data = yield sequelizex.Func.val(yield ShoppingCart.findAll({
            where: {
                shopId: this.params.shopId,
                UserId: (yield auth.user(this)).id
            }
        }));
        debug("data.length:" + data.length);

        // 确实是for循环里面的yield没有起到作用！！！因为for循环没有用co包裹起来。
        // 导致for循环还是异步来循环的，你的yield只是对这个router函数有效果，
        // 对于koa本身，router函数就是一个大的co，所以可以直接用yield！！！
        // 但是对于所有的for循环和map循环都必须用co包裹，才能让for这个东西真正的在yield那个地方停下来！！！

        //上面全是放屁，自己写错了where里面的应该是GoodId....
        //if (data.length) {
        //    for (var idx in data) {
        //        console.log(idx);
        //        db.models.Goods.findOne({
        //            where: {
        //                id: data[idx].GoodId,
        //                shopId: this.params.shopId
        //            }
        //        }).then(function (GoodsData) {
        //            var price = GoodsData.dataValues.price;
        //            console.log(price);
        //            if (util.isNullOrUndefined(price)) {
        //                debug('商品已删除');
        //                ShoppingCart.findOne({
        //                    where: {
        //                        id: data[idx].id
        //                    }
        //                }).then(function (data) {
        //                    data.destroy();
        //                });
        //            } else {
        //                price = price * data[idx].num;
        //                totalprice += price;
        //            }
        //        });
        //    }
        //}

           if(data.length){
               for(var idx in data){
                   var Good = yield db.models.Goods.findById(data[idx].GoodId);
                   if (util.isNullOrUndefined(Good)) {
                       debug('商品已删除');
                       ShoppingCart.findOne({
                           where: {
                               id: data[idx].id
                           }
                       }).then(function (data) {
                           data.destroy();
                       });
                   } else {
                       totalprice += Good.price * data[idx].num * Good.perNum;
                   }
               }
           }
        debug(totalprice);
        var sellprice = yield db.models.shops.findOne({
            where:{
                id:this.params.shopId
            },
            include:[{
                model:db.models.Container
            }]
        });

        sellprice = JSON.parse(sellprice.Container.value).freeLine;
        debug(sellprice);

        this.body = {
            totalprice:totalprice,
            sellprice:sellprice
        }
    });

    router.get('/user/shoppingcart-view', function *() {

        var shoppingCart = yield sequelizex.Func.val(yield ShoppingCart.findAll({
            where: {
                UserId: (yield auth.user(this)).id
            },
            attributes: ['id', 'num', 'GoodId','shopId'],
            include: [{
                model: db.models.Goods,
                attributes: {
                    exclude: ['content']
                }
            },{
                model: db.models.shops,
                attributes:['title'],
                include:[{
                    model:db.models.Container
                }]
            }]
        }));

        //处理购物车数据，根据商店id分类存入新的数组
        function shoppingCartDataParse(shoppingdata){
            var shoppingarray = [];
            var shopsdata = [];
            shopsdata = shoppingdata.map(function(item){
                var d = {};
                d.shopId = item.shopId;
                d.freeLine = JSON.parse(item.shop.Container.value).freeLine;
                d.basicFare = JSON.parse(item.shop.Container.value).basicFare;
                return d;
            });
            shopsdata = ArrayToSet(shopsdata);
            for (var idx in shopsdata){
                var tmparr = [];
                var tmpprice = 0;
                shoppingdata.forEach(function(item){
                   if(item.shopId === shopsdata[idx].shopId){
                       var tempdata = {
                           id: item.id,
                           num: item.num,
                           Good:item.Good,
                           shopId:shopsdata[idx].shopId,
                           GoodId:item.GoodId,
                           shoptitle:item.shop.dataValues.title
                       };
                       tmpprice += tempdata.Good.price * tempdata.num * tempdata.Good.perNum;
                       tmparr.push(tempdata);
                   }
                });
                console.log(tmpprice);
                if(tmpprice > shopsdata[idx].freeLine){
                    shoppingarray.push(tmparr);
                }
            }
            return shoppingarray;
        }

        //数组转集合
        function ArrayToSet(arr){
            var arrid = [];
            var newarr = [];
            for(var x in arr){
                if(arrid.indexOf(arr[x].shopId) === -1){
                    arrid.push(arr[x].shopId);
                    newarr.push(arr[x]);
                }
            }
            return newarr;
        }

        shoppingCart = shoppingCartDataParse(shoppingCart);
        this.body = yield render('phone/shoppingCart.html', {
            title: '购物车',
            shoppingCart: JSON.stringify(shoppingCart)
        });
    });

};